package com.dynabook.ems.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dynabook.ems.annotation.LoginRequired;
import com.dynabook.ems.common.BaseResponse;
import com.dynabook.ems.common.ErrorCode;
import com.dynabook.ems.common.ResultUtils;
import com.dynabook.ems.exception.BusinessException;
import com.dynabook.ems.model.dto.*;
import com.dynabook.ems.model.dto.WorkOrderByBomNumRequest;
import com.dynabook.ems.model.dto.request.WorkOrderBatchApprovalRequest;
import com.dynabook.ems.model.dto.request.WorkOrderBatchDeleteRequest;
import com.dynabook.ems.model.dto.request.WorkOrderBatchRejectRequest;
import com.dynabook.ems.model.dto.request.WorkOrderBatchAcceptanceRequest;
import com.dynabook.ems.model.enums.WorkOrderStatusEnum;
import com.dynabook.ems.model.vo.*;
import com.dynabook.ems.model.vo.WorkOrderByBomNumVO;
import com.dynabook.ems.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工单 控制器
 */
@Api(tags = {"工单 相关接口"})
@RestController
@RequestMapping("/workOrder")
@Slf4j
public class WorkOrderController {
    
    @Resource
    private EmsMainEngineService emsMainEngineService;
    
    @Resource
    private EmsMyBorrowService emsMyBorrowService;


    @Resource
    private EmsBomDetailService emsBomDetailService;


    @Resource
    private EmsWorkOrderService emsWorkOrderService;

    @Resource
    private EmsBomService emsBomService;



    @ApiOperation("测试方法")
    @GetMapping("/test")
    public BaseResponse<UserLoginVO> test(HttpServletRequest request) {
        UserLoginVO userLoginVO = (UserLoginVO) request.getSession().getAttribute("user_login");
        return ResultUtils.success(userLoginVO);
    }
    
    @ApiOperation("根据样品型号查询样品列表")
    @PostMapping("/sampleList")
    public BaseResponse<Page<SampleListVO>> getSampleListByType(@Valid @RequestBody SampleListRequest request) {
        log.info("接收到样品列表查询请求: {}", request);
        
        try {
            Page<SampleListVO> result = emsMainEngineService.getSampleListByType(request);
            return ResultUtils.success(result);
        } catch (Exception e) {
            log.error("查询样品列表失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR,"查询样品列表失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("获取当前用户已借的样品列表")
    @PostMapping("/myBorrowedSampleList")
    public BaseResponse<Page<SampleListVO>> getMyBorrowedSampleList(
            @Valid @RequestBody MyBorrowedSampleListRequest request,
            HttpServletRequest httpRequest) {
        log.info("接收到用户已借样品列表查询请求: {}", request);
        
        try {
            // 从session中获取当前用户信息
            UserLoginVO userLoginVO = (UserLoginVO) httpRequest.getSession().getAttribute("user_login");
            if (userLoginVO == null || userLoginVO.getUserNum() == null) {
                log.error("用户未登录或session中无用户信息");
                return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
            }
            
            String userId = userLoginVO.getUserNum();
            log.info("当前用户ID: {}", userId);
            
            Page<SampleListVO> result = emsMyBorrowService.getMyBorrowedSampleList(request, userId);
            return ResultUtils.success(result);
        } catch (Exception e) {
            log.error("查询用户已借样品列表失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "查询用户已借样品列表失败: " + e.getMessage());
        }
    }
    
    @ApiOperation("根据工单号查询绑定的样品列表")
    @PostMapping("/workOrderSampleList")
    public BaseResponse<Page<SampleListVO>> getSampleListByWorkOrder(@Valid @RequestBody WorkOrderSampleListRequest request) {
        log.info("接收到工单样品列表查询请求: {}", request);

        try {
            Page<SampleListVO> result = emsMainEngineService.getSampleListByWorkOrder(request);
            return ResultUtils.success(result);
        } catch (Exception e) {
            log.error("查询工单样品列表失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "查询工单样品列表失败: " + e.getMessage());
        }

    }
    @ApiOperation("工单选择样品")
    @PostMapping("/selectSamples")
    public BaseResponse<Boolean> selectSamplesForWorkOrder(@Valid @RequestBody WorkOrderSelectSampleRequest request) {
        log.info("接收到工单选择样品请求: {}", request);

        try {
            Boolean result = emsMainEngineService.selectSamplesForWorkOrder(request);
            if (!result) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "所选样品数量和需求数量不符");
            }
            return ResultUtils.success(result);
        } catch (BusinessException e) {
            log.error("工单选择样品业务异常: {}", e.getMessage());
            return ResultUtils.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("工单选择样品失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "工单选择样品失败: " + e.getMessage());
        }
    }
    @ApiOperation("新建工单前调用")
    @PostMapping("/beforeAdd")
    public BaseResponse<Boolean> beforeAdd(
            @Validated @RequestBody BeforeAddRequest request) {
        return emsBomService.beforeAdd(request.getWorkOrderNumber());
    }

    /**
     * 根据工单号更新BOM详情状态为待选状态
     *
     * @param request 更新请求
     * @return 更新结果
     */
    @ApiOperation("根据工单号更新BOM详情状态为待选状态")
    @PostMapping("/updateDetailStatusByWorkOrder")
    @LoginRequired
    public BaseResponse<Boolean> updateDetailStatusByWorkOrder(
            @Validated @RequestBody UpdateBomDetailStatusRequest request) {
        log.info("接收到更新BOM详情状态请求，工单号: {}", request.getWorkOrderNumber());
        return emsBomDetailService.updateDetailStatusByWorkOrder(request.getWorkOrderNumber(),request.getTotalNumber());
    }

    @ApiOperation("取消工单")
    @PostMapping("/cancel")
    @LoginRequired
    public BaseResponse<Boolean> cancelWorkOrder(@Valid @RequestBody CancelWorkOrderRequest request) {
        log.info("接收到取消工单请求，工单号: {}", request.getWorkOrderNumber());
        
        try {
            Boolean result = emsMainEngineService.cancelWorkOrder(request.getWorkOrderNumber());
            return ResultUtils.success(result);
        } catch (BusinessException e) {
            log.error("取消工单业务异常: {}", e.getMessage());
            return ResultUtils.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("取消工单失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "取消工单失败: " + e.getMessage());
        }
    }



    /**
     * 获取工单号
     */
    @ApiOperation("获取工单号")
    @PostMapping("/getWorkOrderNumber")
    @LoginRequired
    public BaseResponse<String> getWorkOrderNumber() {
        return emsWorkOrderService.getWorkOrderNumber();
    }

    /**
     * 新建工单
     *
     * @param workOrderAddRequest 工单新增请求
     * @param request HTTP请求
     * @return 操作结果
     */
    @ApiOperation("新建工单")
    @PostMapping("/add")
    @LoginRequired
    public BaseResponse<Boolean> addWorkOrder(
            @Validated @RequestBody WorkOrderAddRequest workOrderAddRequest, 
            HttpServletRequest request) {
        log.info("接收到新建工单请求: {}", workOrderAddRequest);
        return emsWorkOrderService.addWorkOrder(workOrderAddRequest, request);
    }

    /**
     * 分页查询工单列表
     *
     * @param workOrderListRequest 查询条件
     * @return 工单列表
     */
    @ApiOperation("工单列表")
    @PostMapping("/list")
    public BaseResponse<Page<WorkOrderListVO>> getWorkOrderList(@RequestBody WorkOrderListRequest workOrderListRequest) {
        log.info("查询工单列表，参数: {}", workOrderListRequest);
        Page<WorkOrderListVO> workOrderListPage = emsWorkOrderService.getWorkOrderList(workOrderListRequest);
        return ResultUtils.success(workOrderListPage);
    }


    
    /**
     * 分页查询工单下的BOM详细信息
     *
     * @param request 查询请求（包含分页参数）
     * @return BOM详细信息
     */
    @ApiOperation("查看工单")
    @PostMapping("/getBomDetailByWorkOrderNumber")
    @LoginRequired
    public BaseResponse<WorkOrderBomDetailVO> getBomDetailByWorkOrderNumber(
            @Validated @RequestBody WorkOrderBomDetailRequest request) {
        log.info("接收到根据工单号分页查询BOM详情请求，工单号: {}, 页码: {}, 每页大小: {}", 
                request.getWorkOrderNumber(), request.getCurrent(), request.getPageSize());
        return emsBomDetailService.getBomDetailByWorkOrderNumber(request);
    }

    @ApiOperation("编辑工单回显")
    @PostMapping("/getBomSimpleDetailByWorkOrderNumber")
    @LoginRequired
    public BaseResponse<WorkOrderBomSimpleVO> getBomSimpleDetailByWorkOrderNumber(
            @Validated @RequestBody WorkOrderBomSimpleRequest request) {
        log.info("接收到根据工单号查询BOM简化详情请求，工单号: {}", request.getWorkOrderNumber());
        return emsBomDetailService.getBomSimpleDetailByWorkOrderNumber(request);
    }
    
    /**
     * 分页查询工单审批列表
     *
     * @param workOrderApprovalListRequest 查询条件
     * @return 工单审批列表
     */
    @ApiOperation("工单审批列表")
    @PostMapping("/approvalList")
    public BaseResponse<Page<WorkOrderApprovalListVO>> getWorkOrderApprovalList(
            @RequestBody WorkOrderApprovalListRequest workOrderApprovalListRequest,
            HttpServletRequest request) {
        log.info("查询工单审批列表，参数: {}", workOrderApprovalListRequest);
        
        // 从session中获取当前用户信息
        UserLoginVO userLoginVO = (UserLoginVO) request.getSession().getAttribute("user_login");
        if (userLoginVO == null) {
            log.error("用户未登录，无法查询工单审批列表");
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "请先登录");
        }
        
        // 设置当前用户的部门和科室信息到请求参数中
        workOrderApprovalListRequest.setCurrentUserDepartment(userLoginVO.getDepartment());
        workOrderApprovalListRequest.setCurrentUserSection(userLoginVO.getSectionId());
        log.info("当前用户部门: {}, 科室: {}", userLoginVO.getDepartment(), userLoginVO.getSectionId());
        
        Page<WorkOrderApprovalListVO> workOrderApprovalListPage = emsWorkOrderService.getWorkOrderApprovalList(workOrderApprovalListRequest);
        return ResultUtils.success(workOrderApprovalListPage);
    }

    /**
     * 分页查询样机工单待审批列表
     *
     * @param request 查询条件
     * @return 样机工单待审批列表
     */
    @ApiOperation("样机工单待审批列表")
    @PostMapping("/sampleApprovalList")
    public BaseResponse<Page<WorkOrderSampleApprovalListVO>> getWorkOrderSampleApprovalList(
            @RequestBody WorkOrderSampleApprovalListRequest request) {
        log.info("查询样机工单待审批列表，参数: {}", request);
        Page<WorkOrderSampleApprovalListVO> result = emsMyBorrowService.getWorkOrderSampleApprovalList(request);
        return ResultUtils.success(result);
    }

    /**
     * 批量处理工单申请（同意或拒绝）
     *
     * @param request 批量处理请求
     * @return 操作结果
     */
    @ApiOperation("(课长)批量处理工单申请（同意或拒绝）")
    @PostMapping("/batchProcess")
    @LoginRequired
    public BaseResponse<Boolean> batchProcessWorkOrders(
            @Validated @RequestBody WorkOrderBatchRejectRequest request,
            HttpServletRequest httpServletRequest) {
        log.info("接收到批量处理工单申请请求: {}", request);
        return emsWorkOrderService.batchProcessWorkOrders(request, httpServletRequest);
    }

    /**
     * 批量审批样机工单申请（同意或拒绝）
     *
     * @param request 批量审批请求
     * @param httpRequest HTTP请求
     * @return 操作结果
     */
    @ApiOperation("课长批量审批样机申请（同意或拒绝）")
    @PostMapping("/batchSampleApproval")
    @LoginRequired
    public BaseResponse<Boolean> batchSampleApproval(
            @Validated @RequestBody WorkOrderSampleBatchApprovalRequest request,
            HttpServletRequest httpRequest) {
        log.info("接收到批量样机审批请求: {}", request);
        return emsMyBorrowService.batchSampleApproval(request, httpRequest);
    }

    /**
     * 分页查询样机工单代分配类别列表
     *
     * @param request 查询条件
     * @return 样机工单代分配类别列表
     */
    @ApiOperation("样机工单代分配类别列表")
    @PostMapping("/sampleAssignmentList")
    public BaseResponse<Page<WorkOrderSampleApprovalListVO>> getWorkOrderSampleAssignmentList(
            @RequestBody WorkOrderSampleApprovalListRequest request) {
        log.info("查询样机工单代分配类别列表，参数: {}", request);
        Page<WorkOrderSampleApprovalListVO> result = emsMyBorrowService.getWorkOrderSampleAssignmentList(request);
        return ResultUtils.success(result);
    }

    /**
     * 样品管理员批量审批样机工单申请（同意或拒绝）
     *
     * @param request 批量审批请求
     * @param httpRequest HTTP请求
     * @return 操作结果
     */
    @ApiOperation("样品管理员批量审批样机申请（同意或拒绝）")
    @PostMapping("/sampleManagerBatchApproval")
    @LoginRequired
    public BaseResponse<Boolean> sampleManagerBatchApproval(
            @Validated @RequestBody WorkOrderSampleBatchApprovalRequest request,
            HttpServletRequest httpRequest) {
        log.info("接收到样品管理员批量审批请求: {}", request);
        return emsMyBorrowService.sampleManagerBatchApproval(request, httpRequest);
    }
    
    @ApiOperation("获取工单状态下拉框选项")
    @PostMapping("/getWorkOrderStatusOptions")
    public BaseResponse<List<CategoryOptions>> getWorkOrderStatusOptions() {
        log.info("查询工单状态下拉框选项");
        try {
            List<CategoryOptions> options = Arrays.stream(WorkOrderStatusEnum.values())
                    .map(status -> {
                        CategoryOptions option = new CategoryOptions();
                        option.setName(status.getText());
                        option.setValue(status.getValue().toString());
                        return option;
                    })
                    .collect(Collectors.toList());
            
            return ResultUtils.success(options);
        } catch (Exception e) {
            log.error("获取工单状态选项失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取工单状态选项失败");
        }
    }
    @ApiOperation("批量审批生产中的工单(PM完工)")
    @PostMapping("/batchApprovalInProduction")
    @LoginRequired
    public BaseResponse<Boolean> batchApprovalInProductionWorkOrders(
            @Validated @RequestBody WorkOrderBatchApprovalRequest request,HttpServletRequest httpServletRequest) {
        log.info("批量审批生产中工单，参数: {}", request);
        return emsWorkOrderService.batchApprovalInProductionWorkOrders(request,httpServletRequest);
    }

    /**
     * 根据BOM号查询关联工单信息
     *
     * @param request BOM号查询请求
     * @return 工单信息响应
     */
    @ApiOperation("根据BOM号查询关联工单信息")
    @PostMapping("/getWorkOrdersByBomNum")
    @LoginRequired
    public BaseResponse<WorkOrderByBomNumVO> getWorkOrdersByBomNum(
            @Validated @RequestBody WorkOrderByBomNumRequest request) {
        log.info("接收到根据BOM号查询工单请求: {}", request);
        return emsWorkOrderService.getWorkOrdersByBomNum(request);
    }

    /**
     * 批量验收待验收状态的工单
     *
     * @param request 批量验收请求
     * @return 操作结果
     */
    @ApiOperation("(样品管理员)批量验收待验收状态的工单")
    @PostMapping("/batchAcceptance")
    @LoginRequired
    public BaseResponse<Boolean> batchAcceptanceWorkOrders(
            @Validated @RequestBody WorkOrderBatchAcceptanceRequest request,
            HttpServletRequest httpServletRequest) {
        log.info("批量验收待验收工单，参数: {}", request);
        return emsWorkOrderService.batchAcceptanceWorkOrders(request, httpServletRequest);
    }

    /**
     * 批量删除状态的工单
     *
     * @param request 批量删除请求
     * @return 操作结果
     */
    @ApiOperation("批量删除工单")
    @PostMapping("/batchDelete")
    @LoginRequired
    public BaseResponse<Boolean> batchDelete(
            @Validated @RequestBody WorkOrderBatchDeleteRequest request) {
        log.info("批量验收待验收工单，参数: {}", request);
        return emsWorkOrderService.batchDeleteWorkOrders(request);
    }

    /**
     * 导出工单数据
     *
     * @param workOrderExportRequest 导出请求参数
     * @param response HTTP响应对象
     */
    @ApiOperation("导出工单数据")
    @PostMapping("/export")
    @LoginRequired
    public void exportWorkOrderData(@RequestBody WorkOrderExportRequest workOrderExportRequest, HttpServletResponse response) {
        log.info("导出工单数据，参数: {}", workOrderExportRequest);
        emsWorkOrderService.exportWorkOrderData(workOrderExportRequest, response);
    }

}

